/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rafkind.resrev.web;

import com.rafkind.resrev.web.page.LoginPage;
import org.apache.wicket.Component;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.apache.wicket.authorization.strategies.CompoundAuthorizationStrategy;

/**
 *
 * @author Fictional Hero
 */
public class AuthorizationStrategy extends CompoundAuthorizationStrategy {

  /**
   * Checks that pages marked with {@link Authorized} have a valid user.
   */
  @SuppressWarnings("unchecked")
  private static final class ProtectedComponentChecker implements
      IAuthorizationStrategy {

    public boolean isInstantiationAuthorized(final Class componentClass) {      
      //System.out.println("Attempting to load " + componentClass.getName());
      
      if (componentClass.getAnnotation(Authorized.class) != null 
          && ((Session) Session.get()).getCurrentUser() == null) {
        //System.out.println("Need authorization and user is not logged in!");
        throw new RestartResponseAtInterceptPageException(LoginPage.class);
      }
      //System.out.println("User is logged in ok or we didn't need authorization");
      return true;
    }

    public boolean isActionAuthorized(final Component component, final Action action) {     
      return true;      
    }
  }

  public AuthorizationStrategy() {
    add(new ProtectedComponentChecker());
  }
}